package com.example.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.example.bean.Ftp;

public class FtpUtil {

	private static Logger LOG = LoggerFactory.getLogger(FtpUtil.class);
	/**
	 * 获取FTPClient对象
	 *
	 * @param ftpHost
	 *            FTP主机服务器
	 * @param ftpPassword
	 *            FTP 登录密码
	 * @param ftpUserName
	 *            FTP登录用户名
	 * @param ftpPort
	 *            FTP端口 默认为21
	 * @return
	 * @throws IOException
	 * @throws SocketException
	 */
	public static FTPClient getFTPClient(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort)
			throws SocketException, IOException {
		FTPClient ftpClient = new FTPClient();
		ftpClient = new FTPClient();
		ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器
		ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器
		
		if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
			ftpClient.disconnect();
		}
		return ftpClient;
	}

	/**
	 * 从FTP服务器下载文件
	 * 
	 * @param f
	 * @param localPath
	 *            下载到本地的位置 格式：H:/download
	 * @param fileName
	 *            文件名称
	 * @throws IOException
	 */
	public static void downloadFtpFile(Ftp f, String localPath, String fileName) throws IOException {

		FTPClient ftpClient = null;
		ftpClient = getFTPClient(f.getIpAddr(), f.getUserName(), f.getPwd(), f.getPort());
		ftpClient.setControlEncoding("UTF-8"); // 中文支持
		ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
		//ftpClient.enterLocalPassiveMode();
		ftpClient.enterLocalActiveMode();//主动模式
		ftpClient.changeWorkingDirectory(f.getPath());
		File localFile = new File(localPath + File.separatorChar + fileName);
		OutputStream os = new FileOutputStream(localFile);
		ftpClient.retrieveFile(fileName, os);
		os.close();
		ftpClient.logout();
	}

	/**
	 * Description: 向FTP服务器上传文件
	 * 
	 * @param f
	 * @param fileName
	 *            ftp文件名称
	 * @param input
	 *            文件流
	 * @return 成功返回true，否则返回false
	 * @throws Exception
	 */
	public static boolean uploadFile(Ftp f, String fileName, InputStream input) throws Exception {
		boolean success = false;
		FTPClient ftpClient = null;
		try {
			int reply;
			LOG.info("上传ftp  开始连接");
			ftpClient = getFTPClient(f.getIpAddr(), f.getUserName(), f.getPwd(), f.getPort());
			reply = ftpClient.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftpClient.disconnect();
				return success;
			}
			ftpClient.setControlEncoding("UTF-8"); // 中文支持
			ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
			//ftpClient.enterLocalPassiveMode();//被动模式
			ftpClient.enterLocalActiveMode();//主动模式
			LOG.info("上传ftp  设置目录");
			ftpClient.changeWorkingDirectory(f.getPath());
			LOG.info("上传ftp  开始上传");
			success = ftpClient.storeFile(fileName, input);
			LOG.info("上传ftp  完成");
			input.close();
			ftpClient.logout();
		} catch (IOException e) {
			throw new Exception(e.getMessage());
		} finally {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException ioe) {
					throw new Exception(ioe.getMessage());
				}
			}
		}
		return success;
	}

	public static void main(String[] args) throws Exception {
		Ftp f = new Ftp();
		/*f.setIpAddr("58.62.173.38");
		f.setPort(21);
		f.setUserName("czshj");
		f.setPwd("5<9T&Z-h5?45");*/
		f.setIpAddr("192.168.10.150");
		f.setPort(21);
		f.setUserName("testftp");
		f.setPwd("tcf123666");
		
		f.setPath("output");
		FtpUtil.downloadFtpFile(f, "F:\\test", "test.txt");
	

	}
}
